package com.azzcs.userservicealibaba.service.impl;

import com.azzcs.codeservicecore.service.CodeService;
import com.azzcs.userservicealibaba.domain.UserDO;
import com.azzcs.userservicealibaba.mapper.UserMapper;
import com.azzcs.userservicealibaba.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: wzg
 * @Date: 2021/2/22 下午3:05
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Reference
    private CodeService codeService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Integer register(String email, String password, Integer code) {
        Boolean checkCode = codeService.checkCode(email, code);
        if(!checkCode){
            return 2;
        }
        UserDO userDO = UserDO.builder().email(email).build();
        QueryWrapper queryWrapper =  new QueryWrapper(userDO);
        UserDO dbUser = userMapper.selectOne(queryWrapper);
        if(dbUser != null){
            return 1;
        }
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());
        UserDO registerUser = UserDO.builder()
                .email(email)
                .username("")
                .password(password)
                .createTime(currentTime)
                .updateTime(currentTime)
                .deleted(false)
                .build();
        userMapper.insert(registerUser);
        return 0;
    }

    @Override
    public String createToken(String email) {
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(token,email,30, TimeUnit.MINUTES);
        return token;
    }

    @Override
    public Boolean login(String email, String password) {
        UserDO userDO = UserDO.builder().email(email).build();
        QueryWrapper queryWrapper =  new QueryWrapper(userDO);
        UserDO dbUser = userMapper.selectOne(queryWrapper);
        if(dbUser ==  null){
            return false;
        }
        return dbUser.getPassword().equals(password);
    }

    @Override
    public String getUserInfo(String token) {
        Object o = redisTemplate.opsForValue().get(token);
        return o==null?null:String.valueOf(o);
    }


}
